﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using Newtonsoft.Json.Linq;
using Raven.Client;

namespace DNT.RavenQA.Web.Infrastructure.Filters
{
    public class UserInjectorGlobalFilter : ActionFilterAttribute
    {
        public IDocumentSession Session { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.IsChildAction)
                return;

            var user = filterContext.HttpContext.User;

            if (user is User)
                return;

            var cookie = filterContext.RequestContext
                .HttpContext
                .Request
                .Cookies[FormsAuthentication.FormsCookieName];

            if (cookie.IsNull())
                return;

            var ticket = FormsAuthentication.Decrypt(cookie.Value);

            dynamic userData = JObject.Parse(ticket.UserData);
            String emailAddress = userData.EmailAddress;
            String providerName = userData.ProviderName;

            var instance = Session.Query<User>()
                .SingleOrDefault(x => x.EmailAddress == emailAddress &&
                                      x.ProviderName == providerName);
            filterContext.HttpContext.User = instance;
        }
    }
}